package common

import (
	"gin-YiStudio-V1/common/consts"
	"gin-YiStudio-V1/dao/model"
	"github.com/astaxie/beego/logs"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

func ReleaseToken(user *model.User) (string, error) {
	expiredTime := time.Now().Add(7 * 24 * time.Hour)
	claims := Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expiredTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(),  //token发放的时间
			Issuer:    "ymliang",          //谁发放了token
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	//使用jwt密钥来生成token
	signedString, err := token.SignedString(consts.JwtKey)
	if err != nil {
		logs.Error("生成密钥失败,err=", err)
		return "", err
	}

	return signedString, nil

}

/**
解析token
*/
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (interface{}, error) {
		return consts.JwtKey, nil
	})

	return token, Claims, err
}
